package com.useeinfo.oa.open.admin.task;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.useeinfo.framework.sugar.data.QueryParam;
import com.useeinfo.framework.sugar.data.SelectVO;
import com.useeinfo.framework.sugar.func.excel.ExcelExport;
import com.useeinfo.framework.sugar.tools.AliJsonObjectCover;
import com.useeinfo.framework.sugar.tools.Configuration;
import com.useeinfo.framework.sugar.tools.DateTimeUtils;
import com.useeinfo.framework.sugar.tools.StringConverters;
import com.useeinfo.oa.common.config.ConstantKeySession;
import com.useeinfo.oa.common.config.ExcelExportMap;
import com.useeinfo.oa.common.utils.ResultUtil.ResultDto;
import com.useeinfo.oa.common.utils.ResultUtil.ResultUtil;
import com.useeinfo.oa.modules.base.biz.PositionBiz;
import com.useeinfo.oa.modules.base.biz.SystemUserOrganizationBiz;
import com.useeinfo.oa.modules.base.entity.Enterprise;
import com.useeinfo.oa.modules.base.entity.Position;
import com.useeinfo.oa.modules.base.entity.Resource;
import com.useeinfo.oa.modules.base.entity.SystemUserOrganization;
import com.useeinfo.oa.modules.security.biz.OrganizationBiz;
import com.useeinfo.oa.modules.security.biz.SystemUserBiz;
import com.useeinfo.oa.modules.security.entity.SystemUser;
import com.useeinfo.oa.modules.security.util.SessionKeyUtils;
import com.useeinfo.oa.modules.task.biz.TaskAuditOrderBiz;
import com.useeinfo.oa.modules.task.biz.TaskOrderBiz;
import com.useeinfo.oa.modules.task.biz.TaskOrderLogBiz;
import com.useeinfo.oa.modules.task.entity.TaskAuditOrder;
import com.useeinfo.oa.modules.task.entity.TaskOrder;
import com.useeinfo.oa.modules.task.entity.TaskOrderLog;
import com.useeinfo.oa.modules.task.enums.TaskAssignTypeEnum;
import com.useeinfo.oa.modules.task.enums.TaskOrderLogOperationEnum;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @auther: bin.liu
 * @Date: 2019/6/25 14:15
 * @Description: 任务工单管理action
 */
@Controller
@RequestMapping("/web/admin/taskOrder")
public class TaskOrderAction {

    @Autowired
    private TaskOrderBiz taskOrderBiz;

    @Autowired
    private HttpServletRequest httpServletRequest;

    @Autowired
    private SystemUserOrganizationBiz systemUserOrganizationBiz;

    @Autowired
    private SystemUserBiz systemUserBiz;

    @Autowired
    private TaskOrderLogBiz taskOrderLogBiz;

    @Autowired
    private PositionBiz positionBiz;

    @Autowired
    private OrganizationBiz organizationBiz;

    @Autowired
    private TaskAuditOrderBiz taskAuditOrderBiz;

    /**
     * 打开列表页面
     */
    @RequestMapping("/list")
    public ModelAndView list() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("pages/admin/taskOrder/list");
        return modelAndView;
    }

    /**
     * 查询列表
     */
    @RequestMapping("/listJson")
    @ResponseBody
    public JSONObject listJson(@RequestParam(value = "pageNo", required = false) String pageNowParam,
                               @RequestParam(value = "pageSize", required = false) String pageSizeParam,
                               @RequestParam(value = "serial", required = false) String serial,
                               @RequestParam(value = "orderName", required = false) String orderName,
                               @RequestParam(value = "orderStatus", required = false) String orderStatus,
                               @RequestParam(value = "createUser", required = false) String createUser,
                               @RequestParam(value = "orderTypeName", required = false) String orderTypeName,
                               @RequestParam(value = "createDate1", required = false) String createDate1,
                               @RequestParam(value = "createDate2", required = false) String createDate2,
                               @RequestParam(value = "orderBy", required = false) String orderBy,
                               HttpServletRequest request) {

        // 获取当前选择的企业
        Enterprise sessionEnterprise = SessionKeyUtils.getSessionEnterprise(request);


        QueryParam queryParam = new QueryParam(pageNowParam, pageSizeParam);

        // 只获取当前企业得任务单
        if (!org.springframework.util.StringUtils.isEmpty(sessionEnterprise)) {
            queryParam.getSqlMap().put("enterpriseId", String.valueOf(sessionEnterprise.getId()));
        }

        if (StringUtils.isNotBlank(serial)) {
            queryParam.getSqlMap().put("serial", serial);
        }
        if (StringUtils.isNotBlank(orderName)) {
            queryParam.getSqlMap().put("orderName", orderName);
        }
        if (StringUtils.isNotBlank(orderStatus)) {
            queryParam.getSqlMap().put("orderStatus", orderStatus);
        }
        if (StringUtils.isNotBlank(createUser)) {
            queryParam.getSqlMap().put("createUser", createUser);
        }
        if (StringUtils.isNotBlank(orderTypeName)) {
            queryParam.getSqlMap().put("orderTypeName", orderTypeName);
        }
        if (StringUtils.isNotBlank(createDate1)) {
            queryParam.getSqlMap().put("createDate1", createDate1);
        }
        if (StringUtils.isNotBlank(createDate2)) {
            queryParam.getSqlMap().put("createDate2", createDate2);
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(orderBy)) {
            queryParam.setSqlOrder("order by " + orderBy);
        }
        return taskOrderBiz.findJSONList(queryParam);
    }


    /**
     * 获取编辑页面
     */
    @RequestMapping("/editPage")
    public ModelAndView getEditPage(@RequestParam(value = "id", required = false) String id) {
        // 操作人
        SystemUser systemUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        // 当前企业
        Enterprise sessionEnterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        ModelAndView modelAndView = new ModelAndView();
        TaskOrder taskOrder;
        String img1 = "";
        String img2 = "";
        String img3 = "";
        String img4 = "";
        String img5 = "";
        if (StringUtils.isBlank(id)){
            // id为空 新增
            taskOrder = new TaskOrder();
            taskOrder.setCreateUser(systemUser);
            QueryParam systemUserOrganizationParam = new QueryParam();
            if (sessionEnterprise != null) {
                systemUserOrganizationParam.getSqlMap().put("enterpriseId", StringConverters.null2String(sessionEnterprise.getId()));
            }
            systemUserOrganizationParam.getSqlMap().put("systemUserId", StringConverters.null2String(systemUser.getId()));
            List<SystemUserOrganization> systemUserOrganizations = systemUserOrganizationBiz.findList(systemUserOrganizationParam);
            if (CollectionUtils.isNotEmpty(systemUserOrganizations)) {
                taskOrder.setOrganization(systemUserOrganizations.get(0).getOrganization());
            }
        } else {
            // id不为空，编辑页面
            taskOrder = taskOrderBiz.findModel(StringConverters.null2Long(id));
            if (taskOrder.getTaskPhoto() != null && taskOrder.getTaskPhoto().size() != 0) {
                List<Resource> resources = new ArrayList<>(taskOrder.getTaskPhoto());
                resources.sort((o1, o2) -> o1.getId() < o2.getId() ? -1 : 1);
                img1 = Configuration.getConfigurationByName("hostUrl") + resources.get(0).getPath();
                if (resources.size() > 1) {
                    img2 = Configuration.getConfigurationByName("hostUrl") + resources.get(1).getPath();
                }
                if (resources.size() > 2) {
                    img3 = Configuration.getConfigurationByName("hostUrl") + resources.get(2).getPath();
                }
                if (resources.size() > 3) {
                    img4 = Configuration.getConfigurationByName("hostUrl") + resources.get(3).getPath();
                }
                if (resources.size() > 4) {
                    img5 = Configuration.getConfigurationByName("hostUrl") + resources.get(4).getPath();
                }
            }
        }

        modelAndView.setViewName("pages/admin/taskOrder/edit");
        modelAndView.addObject("taskOrder", taskOrder);
        if (sessionEnterprise != null) {
            modelAndView.addObject("enterprise", sessionEnterprise);
        }

        modelAndView.addObject("img1", img1);
        modelAndView.addObject("img2", img2);
        modelAndView.addObject("img3", img3);
        modelAndView.addObject("img4", img4);
        modelAndView.addObject("img5", img5);
        return modelAndView;
    }


    @RequestMapping("/detail")
    public ModelAndView detail(String id) {
        ModelAndView modelAndView = new ModelAndView();
        TaskOrder taskOrder = taskOrderBiz.findModel(StringConverters.null2Long(id));
        modelAndView.addObject("taskOrder", taskOrder);

        List<SelectVO> list = new ArrayList<>();
        if (StringUtils.isNotBlank(taskOrder.getFlow())) {
            JSONArray jsonArray = JSONArray.parseArray(taskOrder.getFlow());
            if (jsonArray.size() > 0) {
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject j = jsonArray.getJSONObject(i);
                    SelectVO selectVO = new SelectVO();
                    Long organizationId = AliJsonObjectCover.ObjectLong(j, "organizationId");
                    if (organizationId == null) {
                        selectVO.setText("");
                    } else {
                        selectVO.setText(organizationBiz.findModel(StringConverters.null2Long(organizationId)).getOrganizationName());
                    }
                    Long relationId = AliJsonObjectCover.ObjectLong(j, "relationId");
                    String nodeTypeEnum = AliJsonObjectCover.ObjectString(j, "nodeTypeEnum");
                    if ("POSITION".equals(nodeTypeEnum)) {
                        selectVO.setValue("岗位 " + positionBiz.findModel(StringConverters.null2Long(relationId)).getName());
                    } else if ("USER".equals(nodeTypeEnum)) {
                        selectVO.setValue("用户 " + systemUserBiz.findModel(StringConverters.null2Long(relationId)).getUserName());
                    } else if ("SELF".equals(nodeTypeEnum)) {
                        selectVO.setValue("接单人 " + taskOrder.getCreateUser().getUserName());
                    }
                    list.add(selectVO);
                }
            }
        }
        modelAndView.addObject("flow", list);
        modelAndView.setViewName("pages/admin/taskOrder/detail");
        return modelAndView;
    }

    /**
     * 日志页面
     */
    @RequestMapping("/logPage")
    public ModelAndView logListJson(String id, HttpServletRequest request) {
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("taskOrderId", id);
        if (enterprise != null) {
            queryParam.getSqlMap().put("enterpriseId", enterprise.getId() + "");
        }
        queryParam.setSqlOrder(" order by id ");
        List<TaskOrderLog> taskOrderLogs = taskOrderLogBiz.findList(queryParam);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("pages/admin/taskOrder/log");
        modelAndView.addObject("taskOrderLogs", taskOrderLogs);
        return modelAndView;
    }

    /**
     * 删除任务单
     *
     * @param id
     * @return
     */
    @RequestMapping("/delete")
    @ResponseBody
    public ResultDto delete(String id) {
        taskOrderBiz.deleteLogic(taskOrderBiz.findModel(StringConverters.null2Long(id)));
        return ResultUtil.success();
    }

    /**
     * 指定接单人列表跳转页
     *
     * @param taskOrderId
     * @return
     */
    @RequestMapping("/assignUser")
    public ModelAndView assignUser(String taskOrderId) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("taskOrderId", taskOrderId);
        modelAndView.setViewName("pages/admin/taskOrder/assignUser");
        return modelAndView;
    }


    /**
     * 指定人员json数据
     * @param pageNowParam
     * @param pageSizeParam
     * @param taskOrderId 工单id
     * @param searchCode
     * @return JSONObject
     */
    @RequestMapping("/getUserByArea")
    @ResponseBody
    public JSONObject getUserByArea(@RequestParam(value = "pageNo", required = false) String pageNowParam,
                                    @RequestParam(value = "pageSize", required = false) String pageSizeParam,
                                    @RequestParam(value = "taskOrderId", required = false) String taskOrderId,
                                    @RequestParam(value = "searchCode", required = false) String searchCode) {
        TaskOrder taskOrder = taskOrderBiz.findModel(StringConverters.null2Long(taskOrderId));
        // 任务单
        String authorityName = Configuration.getConfigurationByName("taskAuthorityName");
        // 模糊查询 searchCode 需要改公共接口
        return systemUserBiz.getSystemUserJson(taskOrder.getTaskArea() == null ? null : taskOrder.getTaskArea().getId() + "",
                taskOrder.getEnterprise().getId() + "", authorityName, pageNowParam, pageSizeParam,taskOrder.getEnterprise());
    }

    /**
     * 保存指定人
     * @param assignIds
     * @param taskOrderId
     * @return
     */
    @RequestMapping("/saveAssignList")
    @ResponseBody
    public ResultDto saveAssignList(String assignIds, String taskOrderId, HttpServletRequest request) {
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        SystemUser sessionUser = SessionKeyUtils.getSessionUser(request);
        JSONArray jsonArray = JSONArray.parseArray(assignIds);
        TaskOrder taskOrder = taskOrderBiz.findModel(StringConverters.null2Long(taskOrderId));
        Set<SystemUser> systemUsers = taskOrder.getTaskAssignUsers();
        if (systemUsers == null) {
            systemUsers = new HashSet<>();
        }
        for (Object id : jsonArray) {
            SystemUser systemUser = systemUserBiz.findModel(StringConverters.null2Long(id));
            if (systemUser != null) {
                systemUsers.add(systemUser);
            }
        }
        taskOrder.setTaskAssignTypeEnum(TaskAssignTypeEnum.USER);
        taskOrder.setAssign(true);
        taskOrder.setTaskAssignUsers(systemUsers);
        taskOrderBiz.addOrUpdate(taskOrder);
        taskOrderLogBiz.addLog(taskOrder, sessionUser, TaskOrderLogOperationEnum.ASSIGN_USER, enterprise, null);
        return ResultUtil.success();
    }

    /**
     * 指定岗位列表跳转页
     *
     * @param taskOrderId
     * @return
     */
    @RequestMapping("/assignPosition")
    public ModelAndView assignPosition(String taskOrderId) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("taskOrderId", taskOrderId);
        modelAndView.setViewName("pages/admin/taskOrder/assignPosition");
        return modelAndView;
    }

    //指定岗位json数据
    @RequestMapping("/getPositionByArea")
    @ResponseBody
    public JSONObject getPositionByArea(String taskOrderId, HttpServletRequest request,
                                        @RequestParam(value = "pageNo", required = false) String pageNowParam,
                                        @RequestParam(value = "pageSize", required = false) String pageSizeParam) {
        TaskOrder taskOrder = taskOrderBiz.findModel(StringConverters.null2Long(taskOrderId));
        String authorityName = Configuration.getConfigurationByName("taskAuthorityName");
        return positionBiz.getPositionJson(taskOrder.getTaskArea() == null ? null : taskOrder.getTaskArea().getId() + "",
                taskOrder.getEnterprise().getId() + "", authorityName, pageNowParam, pageSizeParam);
    }

    /**
     * 保存指定岗位数据
     *
     * @param assignIds
     * @param taskOrderId
     * @return
     */
    @RequestMapping("/saveAssignPosition")
    @ResponseBody
    public ResultDto saveAssignPosition(String assignIds, String taskOrderId, HttpServletRequest request) {
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        SystemUser sessionUser = SessionKeyUtils.getSessionUser(request);
        JSONArray jsonArray = JSONArray.parseArray(assignIds);
        TaskOrder taskOrder = taskOrderBiz.findModel(StringConverters.null2Long(taskOrderId));
        Set<Position> positions = taskOrder.getTaskAssignPositions();
        if (positions == null) {
            positions = new HashSet<>();
        }
        for (Object id : jsonArray) {
            Position position = positionBiz.findModel(StringConverters.null2Long(id));
            if (positions != null) {
                positions.add(position);
            }
        }
        taskOrder.setAssign(true);
        taskOrder.setTaskAssignTypeEnum(TaskAssignTypeEnum.POSITION);
        taskOrder.setTaskAssignPositions(positions);
        taskOrderBiz.addOrUpdate(taskOrder);
        taskOrderLogBiz.addLog(taskOrder, sessionUser, TaskOrderLogOperationEnum.ASSIGN_POSITION, enterprise, null);
        return ResultUtil.success();
    }


    /**
     * 保存操作
     *
     * @param
     * @return
     */
    @RequestMapping( "/addOrUpdate")
    @ResponseBody
    public ResultDto addOrUpdate(TaskOrder taskOrder,
                                 @RequestParam(value = "createDate1", required = false) String createDate,
                                 @RequestParam(value = "selectAreaId[]", required = false) String selectAreaId,
                                 @RequestParam(value = "selectUserId[]", required = false) String selectUserId,
                                 @RequestParam(value = "recording", required = false) String recording,
                                 @RequestParam(value = "taskOrderStatus", required = false) String taskOrderStatus,
                                 @RequestParam(value = "selectTaskTypeId[]", required = false) String selectTaskTypeId,
                                 @RequestParam(value = "selectCompleteAuditFlowId[]", required = false) String selectCompleteAuditFlowId,
                                 @RequestParam(value = "sImg1", required = false) String sImg1,
                                 @RequestParam(value = "sImg2", required = false) String sImg2,
                                 @RequestParam(value = "sImg3", required = false) String sImg3,
                                 @RequestParam(value = "sImg4", required = false) String sImg4,
                                 @RequestParam(value = "sImg5", required = false) String sImg5,
                                 @RequestParam(value = "pic1", required = false) MultipartFile pic1,
                                 @RequestParam(value = "pic2", required = false) MultipartFile pic2,
                                 @RequestParam(value = "pic3", required = false) MultipartFile pic3,
                                 @RequestParam(value = "pic4", required = false) MultipartFile pic4,
                                 @RequestParam(value = "pic5", required = false) MultipartFile pic5,
                                 @RequestParam(value = "requireFinishTime1", required = false) String requireFinishTime1){
        SystemUser systemUser=SessionKeyUtils.getSessionUser(httpServletRequest);

        return taskOrderBiz.addTaskOrderPC(taskOrder,createDate,selectAreaId,selectUserId,recording,
                                            taskOrderStatus,selectTaskTypeId,selectCompleteAuditFlowId,
                                            sImg1,sImg2,sImg3,sImg4,sImg5,pic1,pic2,pic3,pic4,pic5,systemUser, requireFinishTime1);
    }

    /**
     * 任务单导出
     */
    @RequestMapping(value = "/exportOrder", produces = {"text/plain;charset=UTF-8"})
    @ResponseBody
    public void taskOrderExport(HttpServletResponse response, HttpServletRequest request) {
        String serial = "";
        String orderStatus = "";
        String orderName = "";
        String createDate1 = "";
        String createDate2 = "";
        String orderTypeName = "";
        String createUser = "";

        try {
            serial = URLDecoder.decode(request.getParameter("serial"), "UTF-8");
            orderStatus = URLDecoder.decode(request.getParameter("orderStatus"), "UTF-8");
            orderName = URLDecoder.decode(request.getParameter("orderName"), "UTF-8");
            createDate1 = URLDecoder.decode(request.getParameter("createDate1"), "UTF-8");
            createDate2 = URLDecoder.decode(request.getParameter("createDate2"), "UTF-8");
            orderTypeName = URLDecoder.decode(request.getParameter("orderTypeName"), "UTF-8");
            createUser = URLDecoder.decode(request.getParameter("createUser"), "UTF-8");

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        QueryParam queryParam = new QueryParam();
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);

        if (enterprise != null) {
            queryParam.getSqlMap().put("enterpriseId", enterprise.getId() + "");
        }

        queryParam.getSqlMap().put("serial", serial);
        queryParam.getSqlMap().put("orderStatus", orderStatus);
        queryParam.getSqlMap().put("orderName", orderName);
        if (StringUtils.isNotBlank(orderTypeName)) {
            queryParam.getSqlMap().put("orderTypeName", orderTypeName);
        }
        if(StringUtils.isNotBlank(createDate1)){
            queryParam.getSqlMap().put("createDate1", createDate1);
        }
        if(StringUtils.isNotBlank(createDate2)){
            queryParam.getSqlMap().put("createDate2", createDate2);
        }
        if (StringUtils.isNotBlank(createUser)) {
            queryParam.getSqlMap().put("createUser", createUser);
        }
        JSONArray jsonArray = new JSONArray();
        List<TaskOrder> taskOrders = taskOrderBiz.findList(queryParam);

        for (TaskOrder taskOrder : taskOrders) {
            //审核时间
            QueryParam queryParam1=new QueryParam();
            queryParam1.getSqlMap().put("taskOrderId",taskOrder.getId().toString());
            List<TaskAuditOrder> taskAuditOrders=taskAuditOrderBiz.findList(queryParam1);
            String time="";
            if(CollectionUtils.isNotEmpty(taskAuditOrders)){
                time= DateTimeUtils.formatDateToStringWithTime(taskAuditOrders.get(0).getAuditDate());
            }
            JSONObject jsonObject= taskOrder.toJSONObject();
            jsonObject. put("auditTime",time);
            jsonArray.add(jsonObject);
        }
        try {
            ExcelExport.exportExcelFile("任务清单", ExcelExportMap.TASK_ORDER_LIST_EXPORT_MAP(), jsonArray, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
